package com.sunrise.xdoc.service.impl;

import ar.com.fdvs.dj.core.DynamicJasperHelper;
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
import ar.com.fdvs.dj.domain.DynamicReport;
import com.sunrise.xdoc.constant.ReportFileTypeEnum;
import com.sunrise.xdoc.helper.ReportExporter;
import com.sunrise.xdoc.helper.ServletUtils;
import com.sunrise.xdoc.service.AbstractService;
import com.sunrise.xdoc.service.IReportService;
import com.sunrise.xdoc.servlet.ReportServlet;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.UUID;

/**
 * The Class ReportService.
 *
 * @author Nguyen Duc Dung
 * @since 5/18/13 6:19 PM
 */
@Service("reportService")
public class ReportService extends AbstractService implements IReportService {

    @Override
    public String printReport(DynamicReport report, List<?> data, ReportFileTypeEnum fileTypeEnum) throws JRException, FileNotFoundException {
        JasperReport jasperReport = DynamicJasperHelper.
                generateJasperReport(report, new ClassicLayoutManager(), null);
        JasperPrint jasperPrint = JasperFillManager.
                fillReport(jasperReport, null, new JRBeanCollectionDataSource(data));

        //Unique id all the time.
        UUID uuid = UUID.randomUUID();

        String fileName = "report-" + uuid.toString() + fileTypeEnum.getFileExt();

        String filePath = ServletUtils.getInstance().getRealPath(ReportServlet.REPORT_DIRECTORY, fileName);

        if (fileTypeEnum == ReportFileTypeEnum.PDF) {
            ReportExporter.exportReport(jasperPrint, filePath);
        } else if (fileTypeEnum == ReportFileTypeEnum.EXCEL) {
            ReportExporter.exportReportXls(jasperPrint, filePath);
        }

        return "/service/report?" + ReportServlet.REPORT_FILENAME_PARAMETER + "=" + fileName;
    }
}
